package com.qianbao.service.user.impl;

import com.qianbao.components.excepion.CommonException;
import com.qianbao.components.excepion.ExceptionEnum;
import com.qianbao.components.svresut.Result;
import com.qianbao.components.uuid.SVUuidTool;
import com.qianbao.dao.user.UserDao;
import com.qianbao.domain.user.ModifyPasswordEntity;
import com.qianbao.domain.user.UserEntity;
import com.qianbao.service.user.SVUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;


@Service
public class SVUserServiceImpl implements SVUserService {


    @Autowired
    private UserDao dao;

    @Override
    public int saveUser(UserEntity entity) throws CommonException{

        boolean user = findUserByPhone(entity.getPhone());

        if (user){
            throw new CommonException(ExceptionEnum.Register_fail.getCode(),"手机号已经注册");
        }else {
            String password = new Md5Hash(entity.getPassword(),entity.getPhone(),3).toString();
            entity.setPassword(password);
            entity.setAccount(entity.getPhone());
            entity.setCreateTime(new Date());
            entity.setCustomId(SVUuidTool.getUUID());
            return dao.saveAccount(entity);
        }

    }

    @Override
    public boolean findUserByPhone(String phone) throws CommonException{

        if (phone != null && phone.length() > 0){

            UserEntity entity = dao.findAccountByPhone(phone);

            if (entity == null){
                return false;
            }else {
                return true;
            }

        }else {
            // 手机号不能为空
            throw new CommonException(ExceptionEnum.Request_Params_Invalid.getCode(),"手机号不能为空");
        }
    }


    @Override
    public UserEntity findRegisterUserByPhone(String phone) {
        return dao.findAccountByPhone(phone);
    }

    @Override
    public UserEntity loginAccount(UserEntity entity) throws CommonException{

        try {

            System.out.println("用户的密码:"+entity.getPassword());

            String password = new Md5Hash(entity.getPassword(),entity.getPhone(),3).toString();

            System.out.println("加密后的密码:"+password);

            // 获取token
            UsernamePasswordToken token = new UsernamePasswordToken(entity.getPhone(),password);

            // 获得subject
            Subject subject = SecurityUtils.getSubject();

            // 设置session过期时间
            subject.getSession().setTimeout(7*24*60*60*1000);

            // 获得sessionId
            String sessionId = (String) subject.getSession().getId();

            // 登陆操作
            subject.login(token);
            // 获取用户的登陆数据
            UserEntity userEntity = this.findRegisterUserByPhone(entity.getPhone());

            // 把token返回给客户端
            userEntity.setToken(sessionId);
            userEntity.setPassword("");

            return userEntity;

        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            throw new CommonException(ExceptionEnum.Login_Fail.getCode(),"密码不正确");
        } catch (AuthenticationException e){
            e.printStackTrace();
            throw new CommonException(ExceptionEnum.Login_Fail.getCode(),"手机号没有注册");
        }
    }


    @Override
    public boolean updateUserPassword(UserEntity entity) throws CommonException {

        String password = new Md5Hash(entity.getPassword(),
                entity.getPhone(),
                3).toString();

        int rows = dao.updateUserAccount(entity.getPhone(),password);

        if (rows >=1){
            return true;
        }else {
            return false;
        }

    }


    @Override
    public boolean logoutAccount() throws CommonException {

        Subject subject = null;
        try {
            subject = SecurityUtils.getSubject();
            subject.logout();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            throw new CommonException(
                    ExceptionEnum.Login_out_Fail.getCode(),
                    ExceptionEnum.Login_out_Fail.getMessage()
                    );
        }

    }


    @Override
    public boolean modifyUserPassword(ModifyPasswordEntity entity) throws CommonException {

        String oldPassword = new Md5Hash(entity.getOldPassword(),
                entity.getPhone(),
                3).toString();
        String newPassword = new Md5Hash(entity.getNewPassword(),
                entity.getPhone(),
                3).toString();

        String dataPassword = dao.findUserPasswordByPhone(entity.getPhone());

        if (oldPassword.equals(dataPassword)){

            int rows = dao.updateUserAccount(entity.getPhone(),newPassword);

            if (rows >= 1){
                return true;
            }else {
                return false;
            }

        }else {
            throw new CommonException(
                    ExceptionEnum.Modify_password_notsame.getCode(),
                    ExceptionEnum.Modify_password_notsame.getMessage()
                    );
        }

    }


    @Override
    public void modifyUserDeviceId(String custom_id, String device_id) throws CommonException {

        if (custom_id == null || custom_id.length() == 0 || device_id == null || device_id.length() == 0){

            throw new CommonException(ExceptionEnum.Request_Params_Invalid.getCode(),
                    ExceptionEnum.Request_Params_Invalid.getMessage());
        }

        dao.updateUserDeviceId(custom_id,device_id);
    }

    @Override
    public String findUserCustomIdWithDeviceId(String deviceId) throws CommonException {

        if (deviceId == null || deviceId.length() == 0){
            throw new CommonException(ExceptionEnum.Request_Params_Invalid.getCode(),
                    ExceptionEnum.Request_Params_Invalid.getMessage());
        }else {
            return dao.findUserCustomIdWithDeviceId(deviceId);
        }
    }


}






















